package com.meixiang.activity.homes.service;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.service.CircleImageRecyclerAdapter;
import com.meixiang.entity.CircleImage;
import com.meixiang.entity.services.Reservation;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.inteface.IcalendarOnclick;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.CalendarView;
import com.meixiang.view.LabelLayout;
import com.meixiang.view.StarLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 预约
 * xiejingwen
 */
public class ReservationActivity extends BaseActivity {

    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ll_stars)
    StarLayout llStars;
    @Bind(R.id.btn_reservation)
    Button btnReservation;
    @Bind(R.id.labels)
    LabelLayout labels;
    @Bind(R.id.rv_cosmetologist)
    RecyclerView rvCosmetologist;
    @Bind(R.id.rl_cosmetologist)
    RelativeLayout rlCosmetologist;
    @Bind(R.id.calendar)
    CalendarView calendar;
    @Bind(R.id.tv_select_time)
    TextView tvSelectTime;
    private CircleImageRecyclerAdapter mAdapter;

    private Reservation reservation;
    private int mPosition;
    private String time;
    private String date;
    private String beauticianId;
    private String type,goodsId,price,isMainStore,goodsBody,goodsImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_reservation);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("预约");
    }

    @Override
    protected void initView() {
        type=getIntent().getStringExtra("type");
        goodsId=getIntent().getStringExtra("goodsId");
        price=getIntent().getStringExtra("price");
        isMainStore=getIntent().getStringExtra("isMainStore");
        goodsBody=getIntent().getStringExtra("goodsBody");
        goodsImage=getIntent().getStringExtra("goodsImage");
        MXApplication.mApp.AddActivity(this);
        rvCosmetologist.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
        mAdapter=new CircleImageRecyclerAdapter(this);
        rvCosmetologist.setAdapter(mAdapter);
        //美容师列表点击事件
        mAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, final int position) {
                for (CircleImage item : mAdapter.data) {
                    item.setSelect(false);
                }
                mAdapter.data.get(position).setSelect(true);
                mAdapter.notifyDataSetChanged();
                mPosition = position;
                setBeautician(reservation.getList().get(position));
                getHolidayList(reservation.getList().get(position).getBeauticianId(),goodsId);
            }

        });
        //日历列表点击事件
        calendar.setICalendarOnclickListener(new IcalendarOnclick() {
            @Override
            public void getOnclickDate(String time) {
                Intent intent=new Intent(activity,SelectionTimeActivity.class);
                intent.putExtra("goodsId", getIntent().getStringExtra("goodsId"));
                intent.putExtra("beauticianId", reservation.getList().get(mPosition).getBeauticianId());
                intent.putExtra("date", time);
                startActivityForResult(intent,1);
            }
        });
    }

    @Override
    protected void setData() {
        if (type.equals(GlobalType.ADD_RESERVATION)){
            btnReservation.setText("预约");
        }else{
            btnReservation.setText("修改预约");
        }
        status.showLoading();
        getData(1);
    }
    private void getData(int pageNo){
        HttpParams params=new HttpParams();
        params.put("goodsId",getIntent().getStringExtra("goodsId"));
        params.put("pageSize","1000");
        params.put("pageNo", pageNo + "");
        HttpUtils.post(Config.ORDER_SERVICE, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                reservation = AbJsonUtil.fromJson(result.toString(), Reservation.class);
                if (reservation.getDate() != null) {
                    String[] date = reservation.getDate().split("-");
                    calendar.setNowDate(Integer.parseInt(date[0]), Integer.parseInt(date[1]));
                }

                if (reservation.getList() != null && reservation.getList().size() > 0) {
                    status.removeView();
                    List<CircleImage> data = new ArrayList<>();
                    for (int i = 0; i < reservation.getList().size(); i++) {
                        CircleImage image = new CircleImage(reservation.getList().get(i).getPhotoImage());
                        if (i == 0) {
                            image.setSelect(true);
                            mPosition = i;
                            setBeautician(reservation.getList().get(i));
                            calendar.setUnCheckDate(reservation.getHolidayList());
                        }
                        data.add(image);
                    }
                    mAdapter.addData(data);
                } else {
                    status.showNoData("暂无可预约美容师");
                }
            }

            @Override
            public void onError(String code, String message) {
                status.showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        status.showLoading();
                        getData(1);
                    }
                });
            }
        });
    }
    //设置美容师信息
    private void setBeautician(Reservation.ListBean data){
        tvName.setText(data.getName());
        llStars.setStarNumber(data.getStar());
        labels.setLabels(data.getLabelList());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==200){
            date=data.getStringExtra("date");
            time=data.getStringExtra("time");
            beauticianId=data.getStringExtra("beauticianId");
            if (!AbStrUtil.isEmpty(date)&&!AbStrUtil.isEmpty(time)){
                Drawable drawableLeft= ContextCompat.getDrawable(context,R.mipmap.select_time);
                drawableLeft.setBounds(0,0,drawableLeft.getMinimumWidth(),drawableLeft.getMinimumHeight());
                tvSelectTime.setCompoundDrawables(drawableLeft,null,null,null);
                tvSelectTime.setText("已选择时间:"+date+" "+time);
            }else{
                tvSelectTime.setCompoundDrawables(null,null,null,null);
                tvSelectTime.setText("请选择预约时间");
                date="";
                time="";
                beauticianId="";
            }

        }
    }

    @OnClick({R.id.rl_cosmetologist, R.id.btn_reservation})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_cosmetologist:
                Bundle bundle=new Bundle();
                bundle.putString("beauticianId",reservation.getList().get(mPosition).getBeauticianId());
                startActivity(bundle,CosmetologistActivity.class);
                break;

            case R.id.btn_reservation:
                if (AbStrUtil.isEmpty(time)||AbStrUtil.isEmpty(date)){
                    AbToastUtil.showToast(context,"请先选择预约时间");
                    return;
                }
                //修改预约
                if (type.equals(GlobalType.CHANGE_RESERVATION)){
                    changeReservation();
                }else{
                    //跳转提交订单页面
                    Intent intent=new Intent(ReservationActivity.this,SubmitOrdersActivity.class);
                    intent.putExtra("type", GlobalType.SERVICE_TYPE);
                    intent.putExtra("beauticianId",reservation.getList().get(mPosition).getBeauticianId());
                    intent.putExtra("goodsId",goodsId);
                    intent.putExtra("price",price);
                    intent.putExtra("date",date);
                    intent.putExtra("time", time);
                    intent.putExtra("isMainStore",isMainStore);
                    intent.putExtra("goodsBody",goodsBody);
                    intent.putExtra("goodsImage", goodsImage);
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 修改预约
     */
    private void changeReservation(){
        HttpParams params=new HttpParams();
        params.put("beauticianId",reservation.getList().get(mPosition).getBeauticianId());
        params.put("time",time);
        params.put("date",date);
        params.put("orderId",getIntent().getStringExtra("orderId"));
        HttpUtils.post(Config.CHANGE_RESERVATION, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                AbToastUtil.showToast(context,message);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(context,message);
            }
        });
    }

    /**
     * 获取不可点击美容师时间
     * @param beauticianId
     * @param goodsId
     */
    private void getHolidayList(String beauticianId,String goodsId){
        HttpParams params=new HttpParams();
        params.put("beauticianId",beauticianId);
        params.put("goodsId",goodsId);
        HttpUtils.post(Config.SERVER_URL + "beautician/api/queryRestDate", params, new HttpCallBack(this,"正在获取美容师信息..") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                List<String> holidayList=new Gson().fromJson(result.optJSONArray("holidayList").toString(),new TypeToken<List<String>>(){}.getType());
                calendar.setUnCheckDate(holidayList);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(context,message);
            }
        });
    }
}
